import { useState, useEffect } from 'react';
import { message } from 'antd';
import type { User } from '../types';

export const useAuth = () => {
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 从localStorage获取用户登录状态
    const userStr = localStorage.getItem('currentUser');
    if (userStr) {
      try {
        const user = JSON.parse(userStr);
        setCurrentUser(user);
      } catch (error) {
        console.error('解析用户信息失败:', error);
        localStorage.removeItem('currentUser');
      }
    }
  }, []);

  const login = async (username: string) => {
    setLoading(true);
    try {
      // 模拟登录API调用
      const user: User = {
        id: Date.now().toString(),
        username,
        email: `${username}@example.com`,
      };
      
      setCurrentUser(user);
      localStorage.setItem('currentUser', JSON.stringify(user));
      message.success('登录成功');
      return user;
    } catch (error) {
      message.error('登录失败');
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const logout = () => {
    setCurrentUser(null);
    localStorage.removeItem('currentUser');
    message.success('退出成功');
  };

  const isAuthenticated = !!currentUser;

  return {
    currentUser,
    loading,
    login,
    logout,
    isAuthenticated,
  };
};
